package com.data.modules.online.config.executor;

import com.alibaba.druid.filter.config.ConfigTools;
import com.baomidou.mybatisplus.annotation.DbType;
import com.data.modules.online.cgform.entity.OnlCgformField;
import com.data.modules.online.cgform.util.CgformUtil;
import com.data.modules.online.config.exception.DBException;
import com.data.modules.online.config.service.DbTableHandleI;
import freemarker.template.TemplateException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLSyntaxErrorException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import com.data.common.util.dynamic.db.DbTypeUtils;
import com.data.common.util.ConvertUtils;
import com.data.modules.online.config.datasourceConfig.CgformConfigModel;
import com.data.modules.online.config.datasourceConfig.DataBaseConfig;

@Slf4j
@SuppressWarnings("ALL")
public class DbTableProcess {
    private static final String templatePath = "com/data/modules/online/config/engine/tableTemplate.ftl";

    private static DbTableHandleI dbTableHandle;

    public DbTableProcess(DataBaseConfig bVar) throws SQLException, DBException {
        dbTableHandle = DbTableUtil.m434a(bVar);
    }

    public DbTableProcess() throws SQLException, DBException {
        dbTableHandle = DbTableUtil.m434a((DataBaseConfig) null);
    }

    public static void m416a(CgformConfigModel aVar) throws IOException, TemplateException, HibernateException, SQLException, DBException {
        String message;
        DbType c = DbTableUtil.getDbType(aVar.getDbConfig());
        if (DbTypeUtils.dbTypeIsOracle(c)) {
            ArrayList arrayList = new ArrayList();
            for (OnlCgformField onlCgformField : aVar.getColumns()) {
                if ("int".equals(onlCgformField.getDbType())) {
                    onlCgformField.setDbType("double");
                    onlCgformField.setDbPointLength(0);
                }
                arrayList.add(onlCgformField);
            }
            aVar.setColumns(arrayList);
        }
        String a = FreemarkerHelper.getStringWriterUtf(templatePath, getDbByConfigModel(aVar, c));
        HashMap hashMap = new HashMap();
        DataBaseConfig dbConfig = aVar.getDbConfig();
        hashMap.put("hibernate.connection.driver_class", dbConfig.getDriverClassName());
        hashMap.put("hibernate.connection.url", dbConfig.getUrl());
        hashMap.put("hibernate.connection.username", dbConfig.getUsername());
        String password = dbConfig.getPassword();
        if (password != null) {
            if (dbConfig.getDruid() == null || !ConvertUtils.isNotEmpty(dbConfig.getDruid().getPublicKey())) {
                hashMap.put("hibernate.connection.password", password);
            } else {
                try {
                    hashMap.put("hibernate.connection.password", ConfigTools.decrypt(dbConfig.getDruid().getPublicKey(), password));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        hashMap.put("hibernate.show_sql", true);
        hashMap.put("hibernate.format_sql", true);
        hashMap.put("hibernate.temp.use_jdbc_metadata_defaults", false);
        hashMap.put("hibernate.dialect", DbTypeUtils.getDbDialect(c));
        hashMap.put("hibernate.hbm2ddl.auto", "create");
        hashMap.put("hibernate.connection.autocommit", false);
        hashMap.put("hibernate.current_session_context_class", "thread");
        MetadataSources metadataSources = new MetadataSources(new StandardServiceRegistryBuilder().applySettings(hashMap).build());
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(a.getBytes("utf-8"));
        metadataSources.addInputStream(byteArrayInputStream);
        Metadata buildMetadata = metadataSources.buildMetadata();
        SchemaExport schemaExport = new SchemaExport();
        schemaExport.create(EnumSet.of(TargetType.DATABASE), buildMetadata);
        byteArrayInputStream.close();
        List<Exception> list = schemaExport.getExceptions();
        for (Exception exc : list) {
            if ("java.sql.SQLSyntaxErrorException".equals(exc.getCause().getClass().getName())) {
                SQLSyntaxErrorException sQLSyntaxErrorException = (SQLSyntaxErrorException) exc.getCause();
                if ("42000".equals(sQLSyntaxErrorException.getSQLState())) {
                    if (1064 == sQLSyntaxErrorException.getErrorCode() || 903 == sQLSyntaxErrorException.getErrorCode()) {
                        log.error(sQLSyntaxErrorException.getMessage());
                        throw new DBException("请确认表名是否为关键字。");
                    }
                }
            } else if ("com.microsoft.sqlserver.jdbc.SQLServerException".equals(exc.getCause().getClass().getName())) {
                if (exc.getCause().toString().indexOf("Incorrect syntax near the keyword") != -1) {
                    exc.printStackTrace();
                    throw new DBException(exc.getCause().getMessage());
                }
                log.error(exc.getMessage());
            } else if ((DbType.DM.equals(c) || DbType.DB2.equals(c)) && (message = exc.getMessage()) != null && message.indexOf("Error executing DDL \"drop table") >= 0) {
                log.error(message);
            }
            throw new DBException(exc.getMessage());
        }
    }

    public List<String> getAlterTableStringList(CgformConfigModel aVar) throws DBException, SQLException {
        DbType c = DbTableUtil.getDbType(aVar.getDbConfig());
        String a = DbTableUtil.m430a(aVar.getTableName(), DbTypeUtils.getDbTypeString(c));
        String str = "alter table  " + a + " ";
        List<String> arrayList = new ArrayList<>();
        try {
            Map<String, ColumnMeta> a2 = getColumnMetaMapByDataBaseConfig((String) null, a, aVar.getDbConfig());
            Map<String, ColumnMeta> c2 = getColumnMetaMap(aVar);
            Map<String, String> a3 = getDbFieldNameMap(aVar.getColumns());
            for (String str2 : c2.keySet()) {
                if (!a2.containsKey(str2)) {
                    ColumnMeta aVar2 = c2.get(str2);
                    String str3 = a3.get(str2);
                    if (!a3.containsKey(str2) || !a2.containsKey(str3)) {
                        arrayList.add(str + getAddColumnSql(aVar2));
                        if (!DbTypeUtils.dbTypeIsSQLServer(c) && StringUtils.isNotEmpty(aVar2.getComment())) {
                            arrayList.add(getCommentSql(aVar2));
                        }
                    } else {
                        ColumnMeta aVar3 = a2.get(str3);
                        if (DbType.HSQL.equals(c)) {
                            handleUpdateMultiSql(aVar3, aVar2, a, arrayList);
                        } else {
                            String reNameFieldName = dbTableHandle.getReNameFieldName(aVar2);
                            if (DbTypeUtils.dbTypeIsSQLServer(c)) {
                                arrayList.add(reNameFieldName);
                            } else {
                                arrayList.add(str + reNameFieldName);
                            }
                            if (DbType.DB2.equals(c)) {
                                handleUpdateMultiSql(aVar3, aVar2, a, arrayList);
                            } else {
                                if (!aVar3.equals(aVar2)) {
                                    arrayList.add(str + getUpdateColumnSql(aVar2, aVar3));
                                    if (DbTypeUtils.dbTypeIsPostgre(c)) {
                                        arrayList.add(str + getSpecialHandle(aVar2, aVar3));
                                    }
                                }
                                if (!DbTypeUtils.dbTypeIsSQLServer(c) && !aVar3.mo1291b(aVar2)) {
                                    arrayList.add(getCommentSql(aVar2));
                                }
                            }
                        }
                        arrayList.add(updateDbFiledNameOld(str2, aVar2.getColumnId()));
                    }
                } else {
                    ColumnMeta aVar4 = a2.get(str2);
                    ColumnMeta aVar5 = c2.get(str2);
                    if (DbType.DB2.equals(c) || DbType.HSQL.equals(c)) {
                        handleUpdateMultiSql(aVar4, aVar5, a, arrayList);
                    } else {
                        if (!aVar4.mo1289a(aVar5, c)) {
                            arrayList.add(str + getUpdateColumnSql(aVar5, aVar4));
                        }
                        if (!DbTypeUtils.dbTypeIsSQLServer(c) && !DbTypeUtils.dbTypeIsOracle(c) && !aVar4.mo1291b(aVar5)) {
                            arrayList.add(getCommentSql(aVar5));
                        }
                    }
                }
            }
            for (String str4 : a2.keySet()) {
                if (!c2.containsKey(str4.toLowerCase()) && !a3.containsValue(str4.toLowerCase())) {
                    arrayList.add(str + getDropColumnSql(str4));
                }
            }
            if (DbType.DB2.equals(c)) {
                arrayList.add("CALL SYSPROC.ADMIN_CMD('reorg table " + a + "')");
            }
            return arrayList;
        } catch (SQLException e) {
            throw new RuntimeException();
        }
    }

    private static Map<String, Object> getDbByConfigModel(CgformConfigModel aVar, DbType dbType) {
        String dbTypeString = DbTypeUtils.getDbTypeString(dbType);
        HashMap hashMap = new HashMap();
        for (OnlCgformField onlCgformField : aVar.getColumns()) {
            onlCgformField.setDbDefaultVal(getDouble(onlCgformField.getDbDefaultVal()));
        }
        hashMap.put("entity", aVar);
        hashMap.put("dataType", dbTypeString);
        hashMap.put("db", dbType.getDb());
        return hashMap;
    }

    private Map<String, ColumnMeta> getColumnMetaMapByDataBaseConfig(String str, String str2, DataBaseConfig bVar) throws SQLException {
        Connection connection;
        ResultSet resultSet;
        HashMap hashMap = new HashMap();
        try {
            connection = DbTableUtil.getConnection(bVar);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            connection = null;
        }
        DatabaseMetaData metaData = connection.getMetaData();
        String username = bVar.getUsername();
        DbType c = DbTableUtil.getDbType(bVar);
        if (DbTypeUtils.dbTypeIsOracle(c) || DbType.DB2.equals(c)) {
            username = username.toUpperCase();
        }
        if (DbTypeUtils.dbTypeIsSQLServer(c)) {
            resultSet = metaData.getColumns(connection.getCatalog(), null, str2, "%");
        } else if (DbTypeUtils.dbTypeIsPostgre(c)) {
            resultSet = metaData.getColumns(connection.getCatalog(), "public", str2, "%");
        } else if (DbType.HSQL.equals(c)) {
            resultSet = metaData.getColumns(connection.getCatalog(), "PUBLIC", str2.toUpperCase(), "%");
        } else {
            resultSet = metaData.getColumns(connection.getCatalog(), username, str2, "%");
        }
        while (resultSet.next()) {
            ColumnMeta aVar = new ColumnMeta();
            aVar.setTableName(str2);
            String lowerCase = resultSet.getString("COLUMN_NAME").toLowerCase();
            aVar.setColumnName(lowerCase);
            String string = resultSet.getString("TYPE_NAME");
            int i = resultSet.getInt("DECIMAL_DIGITS");
            aVar.setColunmType(dbTableHandle.getMatchClassTypeByDataType(string, i));
            aVar.setRealDbType(string);
            aVar.setColumnSize(resultSet.getInt("COLUMN_SIZE"));
            aVar.setDecimalDigits(i);
            aVar.setIsNullable(resultSet.getInt("NULLABLE") == 1 ? "Y" : "N");
            aVar.setComment(resultSet.getString("REMARKS"));
            String string2 = resultSet.getString("COLUMN_DEF");
            aVar.setFieldDefault(getDouble(string2) == null ? "" : getDouble(string2));
            hashMap.put(lowerCase, aVar);
        }
        return hashMap;
    }

    private Map<String, ColumnMeta> getColumnMetaMap(CgformConfigModel aVar) {
        HashMap hashMap = new HashMap();
        for (OnlCgformField onlCgformField : aVar.getColumns()) {
            ColumnMeta aVar2 = new ColumnMeta();
            aVar2.setTableName(aVar.getTableName().toLowerCase());
            aVar2.setColumnId(onlCgformField.getId());
            aVar2.setColumnName(onlCgformField.getDbFieldName().toLowerCase());
            aVar2.setColumnSize(onlCgformField.getDbLength().intValue());
            aVar2.setColunmType(onlCgformField.getDbType().toLowerCase());
            aVar2.setIsNullable(onlCgformField.getDbIsNull().intValue() == 1 ? "Y" : "N");
            aVar2.setComment(onlCgformField.getDbFieldTxt());
            aVar2.setDecimalDigits(onlCgformField.getDbPointLength().intValue());
            aVar2.setFieldDefault(getDouble(onlCgformField.getDbDefaultVal()));
            aVar2.setPkType(aVar.getJformPkType() == null ? "UUID" : aVar.getJformPkType());
            aVar2.setOldColumnName(onlCgformField.getDbFieldNameOld() != null ? onlCgformField.getDbFieldNameOld().toLowerCase() : null);
            hashMap.put(onlCgformField.getDbFieldName().toLowerCase(), aVar2);
        }
        return hashMap;
    }

    private Map<String, String> getDbFieldNameMap(List<OnlCgformField> list) {
        HashMap hashMap = new HashMap();
        for (OnlCgformField onlCgformField : list) {
            hashMap.put(onlCgformField.getDbFieldName(), onlCgformField.getDbFieldNameOld());
        }
        return hashMap;
    }

    private String getDropColumnSql(String str) {
        return dbTableHandle.getDropColumnSql(str);
    }

    private String getUpdateColumnSql(ColumnMeta aVar, ColumnMeta aVar2) throws DBException {
        return dbTableHandle.getUpdateColumnSql(aVar, aVar2);
    }

    private String getSpecialHandle(ColumnMeta aVar, ColumnMeta aVar2) {
        return dbTableHandle.getSpecialHandle(aVar, aVar2);
    }

    private void handleUpdateMultiSql(ColumnMeta aVar, ColumnMeta aVar2, String str, List<String> list) {
        dbTableHandle.handleUpdateMultiSql(aVar, aVar2, str, list);
    }

    private String getReNameFieldName(ColumnMeta aVar) {
        return dbTableHandle.getReNameFieldName(aVar);
    }

    private String getAddColumnSql(ColumnMeta aVar) {
        return dbTableHandle.getAddColumnSql(aVar);
    }

    private String getCommentSql(ColumnMeta aVar) {
        return dbTableHandle.getCommentSql(aVar);
    }

    private String updateDbFiledNameOld(String str, String id) {
        return "update onl_cgform_field set DB_FIELD_NAME_OLD = '" + str + "' where ID ='" + id + CgformUtil.f229C;
    }

    private int updateDbFiledNameOld(String str, String str2, Session session) {
        return session.createSQLQuery("update onl_cgform_field set DB_FIELD_NAME_OLD= '" + str + "' where ID ='" + str2 + CgformUtil.f229C).executeUpdate();
    }

    private static String getDouble(String str) {
        if (!StringUtils.isNotEmpty(str)) {
            return str;
        }
        try {
            Double.valueOf(str);
            return str;
        } catch (Exception e) {
            if (!str.startsWith(CgformUtil.f229C) || !str.endsWith(CgformUtil.f229C)) {
                return CgformUtil.f229C + str + CgformUtil.f229C;
            }
            return str;
        }
    }

    public String dropIndexs(String str, String str2) {
        return dbTableHandle.dropIndexs(str, str2);
    }

    public String countIndex(String str, String str2) {
        return dbTableHandle.countIndex(str, str2);
    }


public static java.util.List<java.lang.String> m412a(java.lang.String r8) throws java.sql.SQLException {
        /*
            r1 = 0
            java.util.ArrayList r7 = new java.util.ArrayList
            r7.<init>()
            java.sql.Connection r6 = org.jeecg.modules.online.config.p019c.DbTableUtil.getConnection()     // Catch:{ SQLException -> 0x0060, all -> 0x0053 }
            java.sql.DatabaseMetaData r0 = r6.getMetaData()     // Catch:{ SQLException -> 0x003c, all -> 0x005b }
            r1 = 0
            r2 = 0
            r4 = 0
            r5 = 0
            r3 = r8
            java.sql.ResultSet r1 = r0.getIndexInfo(r1, r2, r3, r4, r5)     // Catch:{ SQLException -> 0x003c, all -> 0x005b }
            r1.getMetaData()     // Catch:{ SQLException -> 0x003c, all -> 0x005b }
        L_0x001a:
            boolean r0 = r1.next()     // Catch:{ SQLException -> 0x003c, all -> 0x005b }
            if (r0 == 0) goto L_0x004d
            java.lang.String r0 = "INDEX_NAME"
            java.lang.String r0 = r1.getString(r0)     // Catch:{ SQLException -> 0x003c, all -> 0x005b }
            boolean r2 = com.data.common.util.ConvertUtils.isEmpty(r0)     // Catch:{ SQLException -> 0x003c, all -> 0x005b }
            if (r2 == 0) goto L_0x0032
            java.lang.String r0 = "index_name"
            java.lang.String r0 = r1.getString(r0)     // Catch:{ SQLException -> 0x003c, all -> 0x005b }
        L_0x0032:
            boolean r2 = com.data.common.util.ConvertUtils.isNotEmpty(r0)     // Catch:{ SQLException -> 0x003c, all -> 0x005b }
            if (r2 == 0) goto L_0x001a
            r7.add(r0)     // Catch:{ SQLException -> 0x003c, all -> 0x005b }
            goto L_0x001a
        L_0x003c:
            r0 = move-exception
            r1 = r6
        L_0x003e:
            org.slf4j.Logger r2 = org.jeecg.modules.online.config.p019c.DbTableProcess.f478a     // Catch:{ all -> 0x005d }
            java.lang.String r3 = r0.getMessage()     // Catch:{ all -> 0x005d }
            r2.error(r3, r0)     // Catch:{ all -> 0x005d }
            if (r1 == 0) goto L_0x004c
            r1.close()
        L_0x004c:
            return r7
        L_0x004d:
            if (r6 == 0) goto L_0x004c
            r6.close()
            goto L_0x004c
        L_0x0053:
            r0 = move-exception
            r6 = r1
        L_0x0055:
            if (r6 == 0) goto L_0x005a
            r6.close()
        L_0x005a:
            throw r0
        L_0x005b:
            r0 = move-exception
            goto L_0x0055
        L_0x005d:
            r0 = move-exception
            r6 = r1
            goto L_0x0055
        L_0x0060:
            r0 = move-exception
            goto L_0x003e
        */
        throw new UnsupportedOperationException("Method not decompiled: com.data.modules.online.config.p019c.DbTableProcess.m412a(java.lang.String):java.util.List");
    }
}
